package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.NursingProjectDto;
import com.zzyl.entity.NursingProject;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.NursingProjectMapper;
import com.zzyl.service.NursingProjectService;
import com.zzyl.vo.NursingProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NursingProjectServiceImpl implements NursingProjectService {
    @Autowired
    private NursingProjectMapper nursingProjectMapper;


    @Override
    public PageResponse<NursingProjectVo> selectByPage(Integer pageNum, Integer pageSize, String name, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Page<NursingProjectVo> page = nursingProjectMapper.selectPageByNameAndStatus(name, status);


        return PageResponse.of(page, NursingProjectVo.class);
    }

    @Override
    public int addNursingProject(NursingProjectDto nursingProjectDto) {
        NursingProject nursingProject = new NursingProject();
        BeanUtil.copyProperties(nursingProjectDto, nursingProject);
        int row = nursingProjectMapper.countByName(nursingProject.getName());
        if (row > 0) {
            throw new BaseException(BasicEnum.UPDATE_NURSINGPROJECT_FAIL);
        }


        return nursingProjectMapper.insert(nursingProject);


    }

    @Override
    public NursingProjectVo selectById(Long id) {

        return nursingProjectMapper.selectById(id);
    }

    @Override
    public int updateNursingProject(NursingProjectDto nursingProjectDto) {

        NursingProject nursingProject = BeanUtil.copyProperties(nursingProjectDto, NursingProject.class);

        String oldName = selectById(nursingProject.getId()).getName();
        String name = nursingProject.getName();
        if (!name.equals(oldName)) {
            int row = nursingProjectMapper.countByName(name);
            if (row > 0) {
                throw new BaseException(BasicEnum.UPDATE_NURSINGPROJECT_FAIL);
            }
        }


        return nursingProjectMapper.update(nursingProject);

    }

    @Override
    public int updateNursingProjectStatus(Long id, Integer status) {
        return nursingProjectMapper.updateStatus(id,status);
    }

    @Override
    public int deleteById(Long id) {
        return nursingProjectMapper.delete(id);
    }

    @Override
    public List<NursingProjectVo> selectAll() {
        return nursingProjectMapper.selectAll();
    }
}
